// 1. React核心库
import React, { useState, useEffect } from 'react';

// 2. UI组件库 - 按字母顺序
import { Card, Form, Input, InputNumber, Button, message, Select, Switch } from 'antd';

// 3. 图标库
import { SaveOutlined, ArrowLeftOutlined } from '@ant-design/icons';

// 4. 专业组件库
import { PageContainer } from '@ant-design/pro-components';

// 5. 工具库
import { useParams, history } from '@umijs/max';

// 7. 项目内部模块
import { apiClients } from '@/services/apiClient';
import { autoLoginInDev } from '@/utils/autoLogin';

// 8. 生成的类型定义 (必须使用，禁止手工定义)
import type { AIModel, AIModelRequest } from '@/services/generated';

const { TextArea } = Input;

const AIModelEdit: React.FC = () => {
  const { id } = useParams<{ id: string }>();
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [providers, setProviders] = useState<any[]>([]);
  const isEdit = !!id;

  // 获取提供商列表
  useEffect(() => {
    const fetchProviders = async () => {
      try {
        await autoLoginInDev();
        const response = await apiClients.aiChat.aiChatProvidersList({});
        setProviders(response.data?.items || []);
      } catch (error) {
        message.error('获取提供商列表失败');
      }
    };
    fetchProviders();
  }, []);

  // 获取模型详情（编辑模式）
  useEffect(() => {
    if (isEdit && id) {
      const fetchData = async () => {
        try {
          await autoLoginInDev();
          const response = await apiClients.aiChat.aiChatModelsRetrieve({ id });
          form.setFieldsValue({
            ...response.data,
            model_params: response.data.model_params ? 
              JSON.stringify(response.data.model_params, null, 2) : ''
          });
        } catch (error) {
          message.error('获取模型数据失败');
        }
      };
      fetchData();
    }
  }, [id, isEdit, form]);

  const onFinish = async (values: any) => {
    try {
      setLoading(true);
      await autoLoginInDev();

      // 处理 model_params
      let modelParams = {};
      if (values.model_params) {
        try {
          modelParams = JSON.parse(values.model_params);
        } catch (error) {
          message.error('模型参数格式错误，请输入有效的JSON');
          return;
        }
      }

      const formData: AIModelRequest = {
        ...values,
        model_params: modelParams,
      };

      if (isEdit) {
        await apiClients.aiChat.aiChatModelsUpdate({ 
          id: id!, 
          aIModelRequest: formData 
        });
        message.success('更新成功');
      } else {
        await apiClients.aiChat.aiChatModelsCreate({ 
          aIModelRequest: formData 
        });
        message.success('创建成功');
      }

      // 跳转到列表页
      history.push('/ai-chat/models');
    } catch (error) {
      message.error(isEdit ? '更新失败' : '创建失败');
    } finally {
      setLoading(false);
    }
  };

  return (
    <PageContainer
      header={{
        title: isEdit ? '编辑AI模型' : '新建AI模型',
        subTitle: isEdit ? `编辑模型 #${id}` : '添加新的AI模型配置',
      }}
    >
      <Card>
        <Form<AIModelRequest>
          form={form}
          layout="vertical"
          onFinish={onFinish}
          initialValues={{
            is_active: true,
            max_tokens: 4096,
            cost_per_1k_tokens: '0.000000',
          }}
        >
          <Form.Item 
            name="name" 
            label="模型名称" 
            rules={[{ required: true, message: '请输入模型名称' }]}
          >
            <Input placeholder="请输入模型显示名称，如：GPT-4" />
          </Form.Item>

          <Form.Item 
            name="model_code" 
            label="模型代码" 
            rules={[{ required: true, message: '请输入模型代码' }]}
          >
            <Input placeholder="请输入模型代码，如：gpt-4、claude-3-opus" />
          </Form.Item>

          <Form.Item 
            name="provider" 
            label="AI提供商" 
            rules={[{ required: true, message: '请选择AI提供商' }]}
          >
            <Select placeholder="请选择AI提供商">
              {providers.map(provider => (
                <Select.Option key={provider.id} value={provider.id}>
                  {provider.name} ({provider.provider_type})
                </Select.Option>
              ))}
            </Select>
          </Form.Item>

          <Form.Item 
            name="max_tokens" 
            label="最大Token限制"
          >
            <InputNumber 
              min={1} 
              max={1000000}
              style={{ width: '100%' }}
              placeholder="请输入最大Token限制"
            />
          </Form.Item>

          <Form.Item 
            name="cost_per_1k_tokens" 
            label="每1k Token成本"
            tooltip="用于成本计算的参考价格"
          >
            <Input placeholder="请输入每1k Token的成本，如：0.002000" />
          </Form.Item>

          <Form.Item 
            name="is_active" 
            label="启用状态"
            valuePropName="checked"
          >
            <Switch checkedChildren="启用" unCheckedChildren="禁用" />
          </Form.Item>

          <Form.Item 
            name="model_params" 
            label="模型参数"
            tooltip="JSON格式的模型特定参数配置"
          >
            <TextArea 
              rows={8}
              placeholder='请输入JSON格式的模型参数，例如：&#10;{&#10;  "temperature": 0.7,&#10;  "top_p": 1.0,&#10;  "presence_penalty": 0.0&#10;}'
            />
          </Form.Item>

          <Form.Item>
            <Button 
              type="primary" 
              htmlType="submit" 
              loading={loading}
              icon={<SaveOutlined />}
              style={{ marginRight: 8 }}
            >
              {isEdit ? '更新' : '创建'}
            </Button>
            <Button 
              icon={<ArrowLeftOutlined />}
              href="/ai-chat/models"
            >
              取消
            </Button>
          </Form.Item>
        </Form>
      </Card>
    </PageContainer>
  );
};

export default AIModelEdit;